package com.xl.rpc.server;

import com.xl.rpc.Request;
import com.xl.rpc.ServiceDescriptor;
import com.xl.rpc.common.utils.ReflectUtils;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 管理RPC暴露的服务
 * @author 辜圆圆
 * @description: gzy的项目
 * @date 2020/3/912:50 AM
 */
@Slf4j
public class ServiceManager {
    // ServiceDescriptor作为key要能去重0
    private Map<ServiceDescriptor,ServiceInstance> services;
    public ServiceManager(){
        this.services = new ConcurrentHashMap<>();
    }

    public <T>void register(Class<T> interfaceClass,T bean){
        Method[] methods =  ReflectUtils.getPublicMethods(interfaceClass);
        for(Method method:methods){
            ServiceInstance sis = new ServiceInstance(bean,method);
            ServiceDescriptor sdp =ServiceDescriptor.from(interfaceClass,method);
            services.put(sdp,sis);
            log.info("register service: {} {}",sdp.getClazz(),sdp.getMethod());
        }
    }
    
    public ServiceInstance lookup(Request request){
        ServiceDescriptor sdp = request.getService();
        return services.get(sdp);
    }
}
